package com.pq.pqojcodesandbox.controller;

import com.pq.pqojcodesandbox.JavaNativeCodeSandbox;
import com.pq.pqojcodesandbox.model.ExecuteCodeRequest;
import com.pq.pqojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {


    //  定义鉴权请求头和密钥
    //定义了一个HTTP请求头字段名auth，用于客户端传递认证信息。
    private static final String AUTH_REQUEST_HEADER = "auth";

    //定义了一个密钥sercrKey，用于验证客户端的合法性。
    private static final String AUTH_REQUEST_SECRET = "sercrKey";

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    /**
     * 功能：返回"ok"，通常用于健康检查（如Kubernetes或负载均衡器探测服务是否存活）。
     * @return
     */
    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request
            , HttpServletResponse response) {
        //  基本的认证 鉴权检查
        String authHeader = response.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        //请求参数检查
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        //调用代码沙箱执行代码
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }
}
